﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Qiniu.Http;
using Qiniu.Storage;
using Qiniu.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Application.Services;
using Microsoft.EntityFrameworkCore;
using Volo.Abp.Application.Dtos;
using BW.WMS.WareHouseStatistics.Page;  // 添加自定义 PagedResultDto 的命名空间
using Microsoft.EntityFrameworkCore;    // 添加 EF Core 扩展方法

namespace BW.WMS.WareHouseAllot.ImgFile
{
    /// <summary>
    /// 图片文件服务实现类
    /// </summary>
    public class ImgFileService : ApplicationService
    {
        private readonly QiniuOptions _qiniuOptions;

        public ImgFileService(IOptions<QiniuOptions> qiniuOptions)
        {
            _qiniuOptions = qiniuOptions.Value;
        }

        /// <summary>
        /// 上传单张图片到七牛云
        /// </summary>
        public async Task<UploadResult> UploadImageToQiniuAsync(IFormFile file)
        {
            try
            {
                // 1. 验证文件
                if (file == null || file.Length == 0)
                {
                    throw new UserFriendlyException("请选择要上传的文件");
                }

                // 2. 验证文件类型
                var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp" };
                var fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant();

                if (!allowedExtensions.Contains(fileExtension))
                {
                    throw new UserFriendlyException("只支持上传图片文件（jpg, jpeg, png, gif, bmp, webp）");
                }

                // 3. 验证文件大小（限制为10MB）
                if (file.Length > 10 * 1024 * 1024)
                {
                    throw new UserFriendlyException("文件大小不能超过10MB");
                }

                // 4. 生成唯一的文件名
                var fileName = GenerateUniqueFileName(file.FileName);

                // 5. 获取上传凭证
                var uploadToken = GetUploadToken();

                // 6. 上传文件到七牛云
                var uploadResult = UploadFileToQiniuAsync(file, fileName, uploadToken);

                // 7. 检查上传结果
                if (uploadResult.Code != 200)
                {
                    throw new UserFriendlyException($"上传失败: {uploadResult.Text}");
                }

                // 8. 返回上传结果
                return new UploadResult
                {
                    Success = true,
                    FileName = fileName,
                    FileUrl = $"{_qiniuOptions.Domain}/{fileName}",
                    FileSize = file.Length,
                    Message = "上传成功"
                };
            }
            catch (UserFriendlyException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new UserFriendlyException($"上传失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 批量上传多张图片到七牛云
        /// </summary>
        public async Task<List<UploadResult>> UploadImagesToQiniuAsync(IFormFileCollection files)
        {
            var results = new List<UploadResult>();

            if (files == null || files.Count == 0)
            {
                throw new UserFriendlyException("请选择要上传的文件");
            }

            // 验证文件数量（限制最多20张图片）
            if (files.Count > 20)
            {
                throw new UserFriendlyException("一次最多只能上传20张图片");
            }

            foreach (var file in files)
            {
                try
                {
                    var result = await UploadImageToQiniuAsync(file);
                    results.Add(result);
                }
                catch (Exception ex)
                {
                    results.Add(new UploadResult
                    {
                        Success = false,
                        FileName = file.FileName,
                        Message = ex.Message
                    });
                }
            }

            return results;
        }

        /// <summary>
        /// 从七牛云删除文件
        /// </summary>
        public async Task<bool> DeleteFileFromQiniuAsync(string fileName)
        {
            try
            {
                if (string.IsNullOrEmpty(fileName))
                {
                    throw new UserFriendlyException("文件名不能为空");
                }

                var mac = new Mac(_qiniuOptions.AccessKey, _qiniuOptions.SecretKey);  // 【修改】使用配置中的AK/SK
                var bucketManager = new BucketManager(mac, new Config());

                var result = bucketManager.Delete(_qiniuOptions.Bucket, fileName);  // 【修改】使用配置中的Bucket

                return result.Code == 200;
            }
            catch (Exception ex)
            {
                throw new UserFriendlyException($"删除文件失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 批量删除文件
        /// </summary>
        public async Task<List<bool>> DeleteFilesFromQiniuAsync(List<string> fileNames)
        {
            var results = new List<bool>();

            if (fileNames == null || fileNames.Count == 0)
            {
                throw new UserFriendlyException("文件名列表不能为空");
            }

            foreach (var fileName in fileNames)
            {
                try
                {
                    var result = await DeleteFileFromQiniuAsync(fileName);
                    results.Add(result);
                }
                catch (Exception)
                {
                    results.Add(false);
                }
            }

            return results;
        }

        /// <summary>
        /// 生成唯一的文件名
        /// </summary>
        private string GenerateUniqueFileName(string originalFileName)
        {
            var extension = Path.GetExtension(originalFileName);
            var timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
            var random = new Random().Next(1000, 9999);

            return $"images/{timestamp}_{random}{extension}";
        }

        /// <summary>
        /// 获取七牛云上传凭证
        /// </summary>
        private string GetUploadToken()
        {
            var putPolicy = new PutPolicy
            {
                Scope = _qiniuOptions.Bucket  // 【修改】使用配置中的Bucket
            };
            putPolicy.SetExpires(3600); // 1小时有效期

            var mac = new Mac(_qiniuOptions.AccessKey, _qiniuOptions.SecretKey);  // 【修改】使用配置中的AK/SK
            return Auth.CreateUploadToken(mac, putPolicy.ToJsonString());
        }

        /// <summary>
        /// 上传文件到七牛云
        /// </summary>
        private HttpResult UploadFileToQiniuAsync(IFormFile file, string fileName, string uploadToken)
        {
            var config = new Config
            {
                Zone = Zone.ZONE_CN_South, // 【修改】使用 ZONE_CN_South，对应华南区域
                UseHttps = true
            };

            var formUploader = new FormUploader(config);

            using var stream = file.OpenReadStream();
            var uploadResult = formUploader.UploadStream(stream, fileName, uploadToken, null);

            return uploadResult;
        }


        /// <summary>
        /// 上传结果类
        /// </summary>
        public class UploadResult
        {
            /// <summary>
            /// 是否成功
            /// </summary>
            public bool Success { get; set; }

            /// <summary>
            /// 文件名
            /// </summary>
            public string FileName { get; set; }

            /// <summary>
            /// 文件URL
            /// </summary>
            public string FileUrl { get; set; }

            /// <summary>
            /// 文件大小
            /// </summary>
            public long FileSize { get; set; }

            /// <summary>
            /// 消息
            /// </summary>
            public string Message { get; set; }
        }
    }
}
